<template>
  <v-container fluid class="fill-height" style="display: block">
    <v-row>
      <v-col cols="12">
        <v-breadcrumbs :items="items"></v-breadcrumbs>
      </v-col>

      <v-col cols="12" md="8">
        <v-card class="fill-height">
          <div class="d-flex flex-no-wrap justify-space-between">
            <div>
              <v-card-title class="headline">数据集</v-card-title>
              <v-card-subtitle>文本</v-card-subtitle>
            </div>

            <v-btn
              class="ma-3"
              depressed
              color="indigo"
              dark
              @click="uploadFiles"
              :loading="loading"
            >
              <span class="mr-2">上传数据</span>
              <v-icon dark>mdi-cloud-upload</v-icon>
            </v-btn>
          </div>
          <v-card-text>{{ activeText || nowData.data }}</v-card-text>
          <audio controls autoplay :src="audioURL"></audio>

          <v-card-actions>
            <v-btn @click="startRecord" depressed color="primary" :disabled="!disabled">开始录音</v-btn>
            <v-btn @click="stopRecord" depressed color="primary" :disabled="disabled">停止录音</v-btn>
          </v-card-actions>
        </v-card>
      </v-col>

      <v-col cols="12" md="4">
        <v-card>
          <v-card-title>
            已采集数据
            <v-spacer></v-spacer>
            <v-btn depressed small color="primary" @click.native="backToCurrent">返回当前</v-btn>
          </v-card-title>
          <v-card-subtitle>文本、音频</v-card-subtitle>

          <v-list nav subheader three-line class="datum">
            <v-list-item-group v-model="active" color="primary">
              <v-list-item v-for="(item, i) in datum" :key="i" @click.native="showCurrent(i)">
                <v-list-item-content>
                  <v-list-item-title v-html="item.filename"></v-list-item-title>
                  <v-list-item-subtitle v-html="item.data"></v-list-item-subtitle>
                </v-list-item-content>
              </v-list-item>
            </v-list-item-group>
          </v-list>
        </v-card>
      </v-col>
    </v-row>
    <v-snackbar v-model="snackbar" dark top timeout="3000" :color="color">
      <v-icon class="mr-2">{{ snackIcon }}</v-icon>
      {{ snackMsg }}
      <template v-slot:action="{ attrs }">
        <v-btn icon v-bind="attrs" @click="snackbar = false">
          <v-icon>mdi-close</v-icon>
        </v-btn>
      </template>
    </v-snackbar>
  </v-container>
</template>

<script>
import RecordRTC from "recordrtc";
import { mapState } from "vuex";
import { Base64ToURL, guid } from "../utils";

export default {
  name: "Record",
  data() {
    return {
      active: undefined,
      snackbar: false,
      items: [
        {
          text: "首页",
          disabled: false,
          exact: true,
          to: { name: "Home" },
        },
        {
          text: "在线录音",
          disabled: true,
          exact: true,
          to: { name: "Record" },
        },
      ],
      activeText: "",
      recorder: null,
      audioURL: "",
      disabled: true,
      snackMsg: "",
      snackIcon: "mdi-alert",
      color: "success",
      loading: false,
    };
  },
  computed: {
    ...mapState({
      nowData: (state) => state.nowData,
      datum: (state) => state.datum,
    }),
  },
  methods: {
    startRecord() {
      const that = this;
      navigator.mediaDevices
        .getUserMedia({
          audio: true,
        })
        .then(async function (stream) {
          that.recorder = RecordRTC(stream, {
            type: "audio",
            mimeType: "audio/wav",
            recorderType: RecordRTC.StereoAudioRecorder,
            desiredSampleRate: 16000,
            numberOfAudioChannels: 1,
          });
          that.recorder.startRecording();
          that.disabled = false;
        })
        .catch(function (error) {
          console.error(error);
          that.showSnackBar(`没有可用的设备`, "mdi-alert", "error");
        });
    },
    stopRecord() {
      const that = this;
      this.recorder.stopRecording(function (audioURL) {
        that.recorder.getDataURL(function (dataURL) {
          // console.log(dataURL);
          let filename = guid();
          let payload = {
            index: that.active,
            src: dataURL,
            filename: filename,
          };
          that.recorder.reset();
          if (that.active !== undefined) {
            that.audioURL = audioURL;
            that.$store.commit("CHANGE_EXIST", payload);
          } else {
            that.$store.dispatch("saveDatum", payload);
            that.$store
              .dispatch("getData")
              .then(function (response) {
                console.log(response);
              })
              .catch(function (err) {
                console.log(err);
              });
          }
          that.disabled = true;
        });
      });
    },
    backToCurrent() {
      this.active = undefined;
      this.activeText = null;
      this.audioURL = Base64ToURL(this.nowData.src);
    },
    showCurrent(index) {
      if (this.active !== undefined) {
        this.activeText = this.datum[index].data;
        this.audioURL = Base64ToURL(this.datum[index].src);
      } else {
        this.activeText = null;
        this.audioURL = Base64ToURL(this.nowData.src);
      }
    },
    showSnackBar(msg, icon, color) {
      this.snackbar = true;
      this.snackMsg = msg;
      this.snackIcon = icon;
      this.color = color;
    },
    uploadFiles(showTips = true) {
      const that = this;
      that.loading = true;
      this.$store
        .dispatch("uploadDatum")
        .then(function (response) {
          if (showTips) {
            that.showSnackBar(
              `共上传${response.count}`,
              "mdi-check-circle",
              "success"
            );
          }
        })
        .catch(function (error) {
          console.log(error);
          that.showSnackBar(`${error.msg}`, "mdi-alert", "warning");
        })
        .finally(function () {
          that.loading = false;
        });
    },
  },
  created() {
    if (JSON.stringify(this.nowData) === "{}") {
      this.$store
        .dispatch("getData")
        .then(function (response) {
          console.log(response);
        })
        .catch(function (err) {
          console.log(err);
        });
    }
  },
};
</script>

<style scoped>
@media (max-width: 768px) {
  .datum {
    height: 300px !important;
  }
}

.datum {
  overflow: hidden;
  overflow-y: scroll;
  height: 500px;
}
</style>